package com.example.util;

import com.example.security.SecurityUser;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UserDetails;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.ResourceBundle;

public class CustomUtil {
    public static Color randomColor(Random ran) {
        int red = ran.nextInt(255);
        int green = ran.nextInt(255);
        int blue = ran.nextInt(255);
        return new Color(red, green, blue);
    }

    public static Font randomFont(Random ran) {
        String[] fontName = {"宋体", "微软雅黑", "黑体", "华文楷体", "楷体", "仿宋"};
        int index = ran.nextInt(fontName.length);
        int style = ran.nextInt(4);
        int size = ran.nextInt(15) + 20;
        return new Font(fontName[index], style, size);
    }

    /**
     * @param phoneNum 手机号码
     * @param minute   有效时间 (分钟)
     * @return
     */
    public static ResultEntity<String> sendShortMessage(String phoneNum, int minute) {
        // 生成验证码
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            sb.append((int) (Math.random() * 10));
        }
        String code = sb.toString();

        ResourceBundle bundle = ResourceBundle.getBundle("properties/shortMessageApi");
        String host = bundle.getString("host");
        String path = bundle.getString("path");
        String method = bundle.getString("method");
        String appcode = bundle.getString("appcode");
        String smsSignId = bundle.getString("smsSignId");
        String templateId = bundle.getString("templateId");
        Map<String, String> headers = new HashMap<>();
        // 最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> queries = new HashMap<>();
        queries.put("mobile", phoneNum);
        queries.put("param", "**code**:" + code + ",**minute**:" + minute);
        queries.put("smsSignId", smsSignId);
        queries.put("templateId", templateId);
        Map<String, String> body = new HashMap<>();

        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, queries, body);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                return ResultEntity.createResultEntity(0, null, 1, code);
            } else {
                String reasonPhrase = statusLine.getReasonPhrase();
                return ResultEntity.createResultEntity(-1, "statusCode: " + statusCode + ", reasonPhrase: " + reasonPhrase, 0, null);
            }
        } catch (Exception e) {
            return ResultEntity.createResultEntity(-1, e.getMessage(), 0, null);
        }
    }

    /**
     * 判断当前请求类型是否是Ajax
     *
     * @param request
     * @return true: 是Ajax请求
     * false: 不是Ajax请求
     */
    public static boolean judgeRequestType(HttpServletRequest request) {
        String acceptHeader = request.getHeader("Accept");
        String xRequestHeader = request.getHeader("X-Requested-With");
        return (acceptHeader != null && acceptHeader.contains("application/json")) || ("XMLHttpRequest").equals(xRequestHeader);
    }

    /**
     * @return 当前用户
     */
    public static SecurityUser currentUser(HttpSession session) {
        SecurityContextImpl securityContext = (SecurityContextImpl) session.getAttribute("SPRING_SECURITY_CONTEXT");
        return ((SecurityUser) securityContext.getAuthentication().getPrincipal());
    }

    /**
     * 获取登录用户IP地址
     */
    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.equals("0:0:0:0:0:0:0:1")) {
            ip = "localhost";
        }
        return ip;
    }
}
